package com.bee.caf_ss_android;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bee.baselibrary.base.BaseActivity;
import com.bee.baselibrary.utils.T;
import com.bee.baselibrary.weight.LoadingDialog;
import com.bee.baselibrary.weight.TitleBar;
import com.bee.caf_ss_android.common.Config;
import com.bee.caf_ss_android.common.GeneralReturnEntity;
import com.bee.caf_ss_android.common.LocalStorage;
import com.bee.caf_ss_android.common.Tools;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author LiHao 南柯一梦宁沉沦 不梦前程不梦卿
 * @org www.fengjishi.com (重庆蜂效电子商务有限公司)
 * @data Created time 2019/4/3.
 * @email 930176087@qq.com
 * @pakeage com.bee.caf_ss_android
 * Personal signature 余生还长 何必慌张
 * Page description : 登录
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.tv_sms_code)
    EditText tvSmsCode;
    @BindView(R.id.tv_send_sms_code)
    TextView tvSendSmsCode;
    @BindView(R.id.btn_button)
    Button btnButton;

    private Activity activity = this ;

    //倒计时
    private LoginVrCountDown loginVrCountDown;

    //加载
    private LoadingDialog loadingDialog ;

    //本地缓存
    private LocalStorage localStorage ;
    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        //判断用户是否已经登录
        localStorage = new LocalStorage(this) ;
        if(!localStorage.getToken().equals("")){
            Tools.refPage(this,PersonalActivity.class,true);
        }

        loadingDialog = new LoadingDialog(this,R.style.DialogStyle) ;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(loginVrCountDown!=null){
            try{
                loginVrCountDown.cancel();
            }catch (Exception e){
            }
        }
    }

    public static final String REGEX_MOBILE = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
    /**
     * 点击获取验证码
     * @param view
     */
    public void onClickSendCode(View view){

        //正在运行中的不处理
        if(isRunVrDownTimer) {
            return;
        }

        String phone = etMobile.getText().toString() ;

        //验证是否是手机号
        if(!vrPhoneReg(phone)){
            return;
        }
        RequestParams requestParams = new RequestParams(Config.InterfaceHost+"app/getVrCode") ;
        requestParams.addBodyParameter("phone",phone) ;
        loadingDialog.show();
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("LoginActive", "onSuccess: "+result);
                GeneralReturnEntity returnEntity = JSONObject.parseObject(result,GeneralReturnEntity.class) ;
                int resCode = returnEntity.getResCode() ;
                Log.d("LoginActive", "resCode: "+resCode);
                if(resCode!=1){
                    T.showLong(activity,returnEntity.getErrMsg());
                }else{
                    //发送成功，开启倒计时
                    loginVrCountDown = new LoginVrCountDown(60*1000,1000) ;
                    loginVrCountDown.start() ;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("LoginActive", "onError: ", ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                loadingDialog.dismiss();
            }
        }) ;
    }

    /**
     * 验证手机号码格式是否正确
     * @param phone
     */
    private Boolean vrPhoneReg(String phone){
        //验证是否是手机号
        if(!Pattern.matches(REGEX_MOBILE, phone)){
            showToast("请输入正确的手机号码！");
            return false;
        }
        return true ;
    }
    /**
     * 点击登录
     * @param view
     */
    public void onClickLoginBtn(View view){
        String phone = etMobile.getText().toString() ;
        String vrCode = tvSmsCode.getText().toString() ;

        if(!vrPhoneReg(phone)) {
            return;
        }

        if(vrCode.equals("")){
            showToast("请输入验证码");
            return;
        }

        RequestParams requestParams = new RequestParams(Config.InterfaceHost+"app/login") ;
        requestParams.addBodyParameter("phone",phone);
        requestParams.addBodyParameter("vrCode",vrCode);

        loadingDialog.show();
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                GeneralReturnEntity entity = JSONObject.parseObject(result,GeneralReturnEntity.class );
                if(entity.getResCode()==1){
                    JSONObject sucessResult = JSONObject.parseObject(entity.getData()) ;
                    if(!sucessResult.getString("resCode").equals("1")){
                        T.showLong(activity,sucessResult.getString("errMsg"));
                    }else{
                        //验证登录成功
                        //将token和顾问信息存入缓存
                        localStorage.setToken(sucessResult.getString("token"));
                        localStorage.setCounselorId(sucessResult.getString("counselorId"));
                        localStorage.setPhone(phone);
                        // 跳转首页
                        Tools.refPage(activity,PersonalActivity.class,true);
                    }
                }else{
                    T.showLong(activity,entity.getErrMsg());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                T.showLong(activity,ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                loadingDialog.dismiss();
            }
        }) ;

    }

    private boolean isRunVrDownTimer = false ;
    /**
     * 验证码倒计时
     */
    public class LoginVrCountDown extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public LoginVrCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            isRunVrDownTimer = true ;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            //Log.d("[timer]", "onTick: "+millisUntilFinished) ;
            tvSendSmsCode.setText((millisUntilFinished/1000)+"秒后可重发");
        }

        @Override
        public void onFinish() {
            //Log.d("[timer]", "onFinish: 我完了");
            tvSendSmsCode.setText("获取验证码");
            //getVrBtn.setBackgroundResource(R.drawable.shape);
            isRunVrDownTimer = false ;
        }
    }
}
